import OpenOPC
import json
import time
def readJSON():
    file = "make_data.json"
    try:
        t = open(file).read()
        data = json.loads(t)
    except Exception, e:
        with open(file) as flow:
            data = flow.read()
            data2 = data.replace("\n","")
            data3 = data2.replace(" ","")
            data = json.loads(data3)
    return data

def tagchk():
    data = readJSON()
    opc = OpenOPC.open_client(data["collector"]["opc_server_ip"])
    opc.connect(data["collector"]["opc_name"])
    f = open("tagchklog","w+")
    rd = open("tagrdlog","a+") #record real reading value
    taglist = data["collector"]["opc_items"][:]
    #step = 500
    #list_n = len(taglist)//step +1
    #nn = 0
    #for k in range(1,list_n):
    for i,tag in enumerate(taglist):
            try:
                tagchk = opc.read(tag)
            except Exception, e:
                    print e
            rd.write(str(i) + ":[\"" + tag + "\",\"" + str(tagchk) + "\",\"" + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) +"\"]," + "\n")
            if tagchk[1] == "Error":
                f.write(str(i) + ":" + tag + ":" + str(tagchk) + "\n")
                data["collector"]["opc_items"].remove(tag)
            print i,":",tag,tagchk


    with open("chkd_make_data.json","w+") as chkd:
        jsontext=json.dumps(data,indent=4,sort_keys=True)
        chkd.write(jsontext)
        chkd.close

    rd.close
    f.close
if __name__ == "__main__":
    while True:
        tagchk()
        #print ("pause 10 second! pause! pause!")
        #time.sleep(10)

